﻿using UnityEngine;
using Lidgren.Network;

public class NetWorkSyncAgent :MonoBehaviour
{
    private static int seq_id;

    public int SyncId;
    public int P_Sencond = 10; //1秒多少个包~
    public float syncTimer = 0;
    public bool isOnlyServerSync;


    private float sync_time
    {
        get
        {
            return 1.0f /(float) P_Sencond;
        }
    }

    public float m_TimeOfLastPackage;
    public float m_TimeBetweenPackages;
    public Vector3 m_DistanceToTravel;

    public float m_PositionSpeed;
    public float m_RotationSpeed = 5;
    protected virtual void Awake()
    {
        SyncId = seq_id++;
       
    }
    private void Start()
    {
        targetPos = transform.position;
        targetRotation = transform.rotation;
        NetworkSyncManager.Instantce.AddSyncObject(this);
    }

    
    private void OnDisable()
    {
        NetworkSyncManager.Instantce.RemoveSyncObject(this);
    }
    protected virtual void OnDestroy()
    {
        
    }
    protected virtual void Update()
    {
        //如果是本地玩家，不同步
        var tankActor = this.GetComponent<TankActor>();
        if (tankActor != null && tankActor.isLocalPlayer)
        {
            return;
        }
        else if(tankActor != null)
        {
            LerpToTarget();
        }else  if (isOnlyServerSync && !RoomMgr.Instantce.isMyRoom )
            LerpToTarget();
    }

    protected virtual void LateUpdate()
    {
        //物品只有房主才进行同步
        if (isOnlyServerSync && !RoomMgr.Instantce.isMyRoom)
            return;
        //如果是本地玩家，Send~
        var tankActor = this.GetComponent<TankActor>();
        if(tankActor != null && !tankActor.isLocalPlayer)
        {
          
                return;
        }

        syncTimer += Time.deltaTime;
        if (syncTimer >= sync_time)
        {
            SendPosSyncPackage();
            syncTimer = 0;
        }
    }

    public virtual  void SendPosSyncPackage()
    {
        NetOutgoingMessage om = NetHandler.Instantce.CreateMessage();
        //om.Write(NetConst.OnPlayerUpdate);
        // om.Write((int) this.transform.position.x * 100);
        //om.Write((int) this.transform.position.y * 100);
        //om.Write((int) this.transform.position.z * 100);
        om.Write(NetConst.OnObjectUpdate);
        om.Write(this.SyncId);
        om.Write((short)(this.transform.position.x * 100));
        om.Write((short)(this.transform.position.y * 100));
        om.Write((short)(this.transform.position.z * 100));
        //om.Write(this.transform.position);
        om.Write((short)(this.transform.rotation.x * 100));
        om.Write((short)(this.transform.rotation.y * 100));
        om.Write((short)(this.transform.rotation.z * 100));
        om.Write((short)(this.transform.rotation.w * 100));
        //om.Write(this.transform.rotation);
        NetHandler.Instantce.SendNetMsgToAll(om, NetDeliveryMethod.UnreliableSequenced);
    }


    public virtual void LerpToTarget()
    {
        var dis = Vector3.Distance(this.transform.position, targetPos);
        if ( dis < 2)
        {
            // this.transform.position += this.m_DistanceToTravel.normalized * this.m_PositionSpeed * 1f * Time.deltaTime;
            //this.transform.position += this.m_DistanceToTravel.normalized * Time.deltaTime * this.m_PositionSpeed;
            if (m_PositionSpeed <= 0)
                this.transform.position = targetPos;
            else
                this.transform.position = Vector3.Lerp(this.transform.position, targetPos, Time.deltaTime * this.m_PositionSpeed);
        }
        else if(dis >= 5)
        {
            Log.Info("直接设置Dis");
            this.transform.position = targetPos;
        }
       
      
        //this.transform.rotation = Quaternion.Lerp(this.transform.rotation, targetRotation, Time.deltaTime * m_RotationSpeed);
        this.transform.rotation = targetRotation;
        //this.transform.position = Vector3.Lerp(this.transform.position, targetPos, Time.deltaTime);
    }

    public Vector3 targetPos;
    public Quaternion targetRotation;
    public virtual void OnHandlerSyncPackage(NetIncomingMessage msg)
    {
      
        msg.Position = 0;
        var netConst = msg.ReadByte();
        var id = msg.ReadInt32();
        var pos_x = msg.ReadInt16();
        var pos_y = msg.ReadInt16();
        var pos_z = msg.ReadInt16();
        var ro_x = msg.ReadInt16();
        var ro_y = msg.ReadInt16();
        var ro_z = msg.ReadInt16();
        var ro_w = msg.ReadInt16();
        targetPos.x = pos_x / 100.0f; ; targetPos.y = pos_y / 100.0f; ; targetPos.z = pos_z / 100.0f; ;
        targetRotation.x = ro_x / 100.0f; targetRotation.y = ro_y / 100.0f; ; targetRotation.z = ro_z / 100.0f; ; targetRotation.w = ro_w / 100.0f; ;
        //targetPos = msg.ReadVector3();
        //targetRotation = msg.ReadQuaternion();
        // targetPos = position;
        // targetRotation = rotation;

        this.m_TimeBetweenPackages = Time.time - this.m_TimeOfLastPackage;
        m_TimeBetweenPackages = Mathf.Clamp(m_TimeBetweenPackages, 0.01f, int.MaxValue);
        this.m_TimeOfLastPackage = Time.time;

        m_DistanceToTravel = targetPos - this.transform.position;

       this.m_PositionSpeed = this.m_DistanceToTravel.magnitude / this.m_TimeBetweenPackages;
       //this.m_PositionSpeed =  Mathf.Clamp( this.m_TimeBetweenPackages - sync_time,0,5) * 1000;
    }
    
}
